package com.saltedfish.tool.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;
import androidx.core.content.FileProvider;
import com.saltedfish.tool.constant.IntConstant;
import com.saltedfish.tool.constant.StringConstant;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import cn.droidlover.xdroidmvp.util.ToastUtils;

import static android.app.Activity.RESULT_OK;


public class PhotoUtil {

    private static final String TAG = "PhotoUtils";
    public static final int CODE_CAMERA_REQUEST = 1111;
    public static final int CODE_GALLERY_REQUEST = 2222;
    public static final int CODE_CROP_REQUEST = 3333;
    private static final int OUTPUT_X = 960;
    private static final int OUTPUT_Y = 960;
    public static final int SELECT_PICTURE = 0000;


    private static Uri imageUri;
    private static Uri cropImageUri;

    /**
     * activity 的result 回调
     * @param context
     * @param requestCode
     * @param resultCode
     * @param data
     * @return
     */
    public static String onActivityResult(Activity context, int requestCode, int resultCode, Intent data) {
        String path = "";
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                //拍照完成回调
                case CODE_CAMERA_REQUEST:
                    cropImageUri = getCropImageUri();
                    cropImageUri(context);
                    break;
                //访问相册完成回调
                case CODE_GALLERY_REQUEST:
                    if (hasSdcard()) {
                        cropImageUri = getCropImageUri();
                        imageUri = Uri.parse(PhotoUtil.getPath(context, data.getData()));
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            imageUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", new File(imageUri.getPath()));
                        }
                        cropImageUri(context);
                    } else {
                        Toast.makeText(context,"请先安装SD卡", Toast.LENGTH_LONG).show();
                    }
                    break;
                case CODE_CROP_REQUEST:
                    path = cropImageUri.getPath();
                    break;
                default:
            }
        }
        return path;
    }


    /**
     * 调用相机拍照
     * @param activity
     */
    public static void takePicture(Activity activity) {
        createImageDirectory();
        imageUri = buildImageUri(activity);
        //调用系统相机
        Intent intentCamera = new Intent();
        intentCamera.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        //将拍照结果保存至photo_file的Uri中，不保留在相册中
        intentCamera.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
        activity.startActivityForResult(intentCamera, CODE_CAMERA_REQUEST);
    }

    /**
     * 选择相册图片
     */
    public static void selectPhoto(Activity activity) {

        Intent albumIntent = new Intent(Intent.ACTION_PICK, null);
        albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        activity.startActivityForResult(albumIntent, SELECT_PICTURE);

    }

    /**
     * 打开相册
     * @param activity
     */
    public static void openGallery(Activity activity) {
        createImageDirectory();
        Intent albumIntent = new Intent(Intent.ACTION_PICK, null);
        albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//        Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
//        photoPickerIntent.setType("image/*");
        activity.startActivityForResult(albumIntent, CODE_GALLERY_REQUEST);
    }


    /**
     * 进行图片裁剪
     * @param activity
     */
    public static void cropImageUri(Activity activity) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.setDataAndType(imageUri, "image/*");
        //发送裁剪信号
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1.2);
        intent.putExtra("outputX", OUTPUT_X);
        intent.putExtra("outputY", OUTPUT_Y);
        intent.putExtra("scale", true);
        //将剪切的图片保存到目标Uri中
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cropImageUri);
        //1-false用uri返回图片
        //2-true直接用bitmap返回图片（此种只适用于小图片，返回图片过大会报错）
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        activity.startActivityForResult(intent, CODE_CROP_REQUEST);
    }


    public static void takePhoto(Activity context,File takePhotoImageFile) {
        //用来打开相机的Intent
        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //这句作用是如果没有相机则该应用不会闪退，要是不加这句则当系统没有相机应用的时候该应用会闪退
        if (takePhotoIntent.resolveActivity(context.getPackageManager()) != null) {
            if (takePhotoImageFile != null) {
                Log.i("take photo", takePhotoImageFile.getAbsolutePath());
               Uri mImageUri  = buildImageUri(context,takePhotoImageFile);
                //将用于输出的文件Uri传递给相机
                takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
                //启动相机
                context.startActivityForResult(takePhotoIntent, IntConstant.TAKE_PHOTO);
            }
        }
    }


    /**
     * 读取uri所在的图片
     *
     * @param uri      图片对应的Uri
     * @param mContext 上下文对象
     * @return 获取图像的Bitmap
     */
    public static Bitmap getBitmapFromUri(Uri uri, Context mContext) {
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), uri);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将拍的照片添加到相册
     */
    public static void setGalleryAddPictures(File file, Context mContext) {
        //把文件插入到系统图库
//        try {
//            MediaStore.Images.Media.insertImage(mContext.getContentResolver(),
//                    file.getAbsolutePath(), file.getName(), null);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
        //通知图库更新
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file));
        mContext.sendBroadcast(mediaScanIntent);
    }

    private static Uri getCropImageUri(File file){
        return Uri.fromFile(file);
    }
    /**
     * @param context 上下文对象
     * @param uri     当前相册照片的Uri
     * @return 解析后的Uri对应的String
     */
    @SuppressLint("NewApi")
    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        String pathHead = "file:///";
        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return pathHead + Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);

                final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return pathHead + getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return pathHead + getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return pathHead + getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return pathHead + uri.getPath();
        }
        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null){
                cursor.close();
            }
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    private static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    public static Uri buildImageUri(Context context){
        Uri imageUri;
        File fileUri = new File(StringConstant.getImageDir() + "photo.jpg");
        //通过FileProvider创建一个content类型的Uri
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", fileUri);
        }else {
            imageUri = Uri.fromFile(fileUri);
        }
        return imageUri;
    }

    public static Uri buildImageUri(Context context,File fileUri){
        Uri imageUri;
        //通过FileProvider创建一个content类型的Uri
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", fileUri);
        }else {
            imageUri = Uri.fromFile(fileUri);
        }
        return imageUri;
    }

    public static Uri getCropImageUri(){
        return Uri.fromFile(new File(StringConstant.getImageDir() +"photo.jpg"));
    }

    public static File createImageFile() {
        createImageDirectory();
        File  fileUri = new File(StringConstant.getImageDir() + System.currentTimeMillis() + ".jpg");
        return fileUri;
    }

    /**
     * 新创建一个图片地址路径
     *
     * @return
     */
    public static String createNewsImageFile() {
        // 照片全路径
        String fileName = "";
        // 文件夹路径
        String imageName = "compress_" + String.valueOf(System.currentTimeMillis()) + ".jpg";
        fileName = StringConstant.getImageDir() + imageName;
        File file = new File(StringConstant.getImageDir());
        file.mkdirs();// 创建文件夹
        File fileShow = new File(fileName);
        if (fileShow.exists()) {
            fileShow.delete();
        }
        return fileName;
    }


    public static String createImageDirectory(){
        File directory = new File(StringConstant.getImageDir());
        if(!directory.exists()){
            directory.mkdir();
        }
        return StringConstant.getImageDir();
    }

    /* 根据文件路径转换为bitmap */
    public static Bitmap getBitemapFromFile(String fileName) {
        try {
            BitmapFactory.Options opt = new BitmapFactory.Options();
            opt.inPreferredConfig = Bitmap.Config.RGB_565;
            opt.inPurgeable = true;
            opt.inInputShareable = true;
            //   opt.inSampleSize = 8;
            return BitmapFactory.decodeFile(fileName, opt);


        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 检查设备是否存在SDCard的工具方法
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);
    }

    public static Bitmap decodeBitmap(String httpUrl) {
        URL url = null;
        Bitmap bm = null;
        try {
            url = new URL(httpUrl);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            InputStream in = url.openStream();
            bm = BitmapFactory.decodeStream(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bm;
    }

    /**
     * 保存图片到图库的方法
     *
     * @param context
     * @param bmp
     */
    public static void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File directory = new File(StringConstant.getImageDirs());
        if (!directory.exists()) {
            directory.mkdir();
        }

        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(directory, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 其次把文件插入到系统图库
        try {
            ToastUtils.showMessage(context,"图片保存至系统相册");
            MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
            Uri uri = Uri.fromFile(file);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            FileSizeUtil.deleteFiles(file);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 最后通知图库更新
        //   context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/Teayork")));

    }



}
